package util;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class PortScanUtil {

    private final static PortScanUtil portScanUtil = new PortScanUtil();
    private static AtomicInteger port = new AtomicInteger(26951);
    private static Runnable scanRun = () -> {
        int tempPort = port.getAndIncrement();
        if (tempPort % 1000 == 0) {
            System.out.println("当前值：" + port.get());
        }
        if (portScanUtil.isHostConnectable("121.89.206.174", tempPort, 1000)) {
            System.out.println(tempPort);
        }
    };

    public static void main(String[] args) {
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(50);
        for (int i = 0; i < 50; i++) {
            scheduledExecutorService.scheduleAtFixedRate(scanRun, 0, 105, TimeUnit.MILLISECONDS);
        }
        while (true) {
            if (port.get() == 65535) {
                scheduledExecutorService.shutdown();
                break;
            }
        }
    }

    public static boolean isHostReachable(String host, Integer timeOut) {
        try {
            return InetAddress.getByName(host).isReachable(timeOut);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean isHostConnectable(String host, int port, int timeOut) {
        Socket socket = new Socket();
        try {
            socket.connect(new InetSocketAddress(host, port), timeOut);
        } catch (IOException e) {
//            e.printStackTrace();
            return false;
        } finally {
            try {
                socket.close();
                socket = null;
            } catch (IOException e) {
//                e.printStackTrace();
            }
        }
        return true;
    }
}
